<?php

declare(strict_types=1);
/**
 * Author: Zane
 * Email: 873934580@qq.com
 * Date: 2023/7/14.
 */

namespace App\Http\Controllers\Home;

use App\Http\Controllers\Controller;
use Illuminate\Support\Str;

class HomeController extends Controller
{
    public function index()
    {
        return view('default.index');
    }

    /**
     * 自定义渲染方式.
     */
    public function render()
    {
        return view($this->getTemplateName());
    }

    public function cate()
    {
        $cate = request()->route('cate');
        $id = 0;
        if ('product' === $cate) {
            $template = 'default.product';
            $id = request()->route('id', 5);
        } elseif ('article' === $cate) {
            $template = 'default.article';
            $id = request()->route('id', 3);
        } else {
            $template = $this->getTemplateName();
        }

        return view($template, compact('id'));
    }

    public function details()
    {
        $cate = request()->route('cate');
        $id = (int) request()->route('id');
        if ('product' === $cate) {
            $template = 'default.product_details';
            $data = modelBuild('liquor')->newQuery()->find($id)->toArray();
        } else {
            $template = 'default.article_details';
            $data = modelBuild('article')->newQuery()->find($id)->toArray();
        }

        return view($template, compact('id', 'data'));
    }

    /**
     * 根据请求参数路径匹配对应模版（如果存在，不存在返回404）.
     *
     * @return string
     */
    private function getTemplateName(): string
    {
        $url = request()->server('REQUEST_URI');
        $path = Str::replace('.html', '', Str::before($url, '?'));
        $paths = explode('/', $path);
        // TODO 需要根据后台选择模版的情况获取模版内容
        $file = resource_path('views/default'.$path.'.blade.php');
        // 模版不存在
        if (!file_exists($file)) {
            return config('view.404');
        }
        $temp = '';
        foreach ($paths as $path) {
            if (!$path) {
                continue;
            }

            $temp = '' === $temp ? $path : $temp.'.'.$path;
        }

        return 'default.'.$temp;
    }
}
